<template>
  <div class="playback-container">
    <div class="playback-header">
      <h1>视频与行为回放</h1>
      <div class="candidate-info">
        <span>{{ candidate.name }}</span>
        <span class="separator">|</span>
        <span>{{ candidate.position }}</span>
        <span class="separator">|</span>
        <span>{{ formatDate(candidate.interviewDate) }}</span>
      </div>
    </div>
    
    <div class="playback-content">
      <!-- 视频播放器 -->
      <div class="video-section">
        <div class="video-player">
          <video 
            ref="videoPlayer" 
            controls 
            :src="videoUrl"
            @timeupdate="handleTimeUpdate"
            @loadedmetadata="handleVideoLoaded"
          >
            您的浏览器不支持视频播放
          </video>
          
          <!-- 播放控制栏 -->
          <div class="video-controls">
            <div class="control-left">
              <el-button 
                :icon="isPlaying ? 'VideoPause' : 'VideoPlay'"
                @click="togglePlay"
                circle
              />
              <span class="time-display">
                {{ formatTime(currentTime) }} / {{ formatTime(duration) }}
              </span>
            </div>
            
            <div class="control-center">
              <el-slider 
                v-model="currentTime" 
                :max="duration"
                @change="seekTo"
                class="progress-slider"
              />
            </div>
            
            <div class="control-right">
              <el-select v-model="playbackSpeed" @change="changeSpeed" size="small">
                <el-option label="0.5x" value="0.5" />
                <el-option label="1x" value="1" />
                <el-option label="1.25x" value="1.25" />
                <el-option label="1.5x" value="1.5" />
                <el-option label="2x" value="2" />
              </el-select>
            </div>
          </div>
        </div>
        
        <!-- 跳转锚点 -->
        <div class="anchor-points">
          <h4>快速跳转</h4>
          <div class="anchor-list">
            <div 
              v-for="anchor in anchorPoints" 
              :key="anchor.id"
              class="anchor-item"
              @click="jumpToTime(anchor.time)"
            >
              <div class="anchor-time">{{ formatTime(anchor.time) }}</div>
              <div class="anchor-label">{{ anchor.label }}</div>
              <div class="anchor-stage">{{ anchor.stage }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 行为分析面板 -->
      <div class="analysis-panel">
        <!-- 时间轴行为标记 -->
        <div class="timeline-section">
          <h4>时间轴行为标记</h4>
          <div class="timeline-container">
            <div class="timeline-track" ref="timelineTrack">
              <div class="timeline-progress" :style="{ width: progressPercentage + '%' }"></div>
              
              <div 
                v-for="behavior in behaviorMarkers" 
                :key="behavior.id"
                class="behavior-marker"
                :class="behavior.type"
                :style="{ left: (behavior.time / duration) * 100 + '%' }"
                @click="jumpToTime(behavior.time)"
                :title="behavior.description"
              >
                <div class="marker-dot"></div>
                <div class="marker-label">{{ behavior.label }}</div>
              </div>
            </div>
            
            <div class="timeline-legend">
              <div class="legend-item">
                <div class="legend-dot hesitation"></div>
                <span>犹豫</span>
              </div>
              <div class="legend-item">
                <div class="legend-dot confidence"></div>
                <span>自信</span>
              </div>
              <div class="legend-item">
                <div class="legend-dot emotion"></div>
                <span>情绪高峰</span>
              </div>
              <div class="legend-item">
                <div class="legend-dot stress"></div>
                <span>压力反应</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 行为证据列表 -->
        <div class="evidence-section">
          <div class="evidence-header">
            <h4>行为证据</h4>
            <el-button type="primary" size="small" @click="addEvidence">
              <el-icon><Plus /></el-icon>
              添加证据
            </el-button>
          </div>
          
          <div class="evidence-list">
            <div 
              v-for="evidence in evidenceList" 
              :key="evidence.id"
              class="evidence-item"
            >
              <div class="evidence-header-row">
                <div class="evidence-time" @click="jumpToTime(evidence.time)">
                  {{ formatTime(evidence.time) }}
                </div>
                <el-tag :type="getEvidenceTagType(evidence.type)" size="small">
                  {{ evidence.type }}
                </el-tag>
                <div class="evidence-actions">
                  <el-button type="text" size="small" @click="editEvidence(evidence)">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button type="text" size="small" @click="deleteEvidence(evidence.id)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
              
              <div class="evidence-content">
                <p>{{ evidence.description }}</p>
                <div class="evidence-meta">
                  <span class="evidence-category">{{ evidence.category }}</span>
                  <span class="evidence-confidence">置信度: {{ evidence.confidence }}%</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 实时分析数据 -->
        <div class="realtime-analysis">
          <h4>实时分析数据</h4>
          <div class="analysis-grid">
            <div class="analysis-item">
              <div class="analysis-label">当前情绪</div>
              <div class="analysis-value">
                <el-tag :type="getCurrentEmotionType()">
                  {{ currentAnalysis.emotion }}
                </el-tag>
              </div>
            </div>
            
            <div class="analysis-item">
              <div class="analysis-label">语速</div>
              <div class="analysis-value">{{ currentAnalysis.speechRate }} 词/分</div>
            </div>
            
            <div class="analysis-item">
              <div class="analysis-label">眼神交流</div>
              <div class="analysis-value">
                <el-progress 
                  :percentage="currentAnalysis.eyeContact" 
                  :stroke-width="4"
                  :show-text="false"
                />
                <span>{{ currentAnalysis.eyeContact }}%</span>
              </div>
            </div>
            
            <div class="analysis-item">
              <div class="analysis-label">手势频率</div>
              <div class="analysis-value">{{ currentAnalysis.gestureFrequency }} 次/分</div>
            </div>
            
            <div class="analysis-item">
              <div class="analysis-label">停顿时长</div>
              <div class="analysis-value">{{ currentAnalysis.pauseDuration }}s</div>
            </div>
            
            <div class="analysis-item">
              <div class="analysis-label">语调变化</div>
              <div class="analysis-value">
                <el-progress 
                  :percentage="currentAnalysis.toneVariation" 
                  :stroke-width="4"
                  :show-text="false"
                />
                <span>{{ currentAnalysis.toneVariation }}%</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 底部操作栏 -->
    <div class="playback-footer">
      <div class="footer-actions">
        <el-button @click="exportAnalysis">
          <el-icon><Download /></el-icon>
          导出分析报告
        </el-button>
        <el-button @click="saveBookmarks">
          <el-icon><Collection /></el-icon>
          保存书签
        </el-button>
        <el-button type="primary" @click="backToReport">
          <el-icon><Back /></el-icon>
          返回评估报告
        </el-button>
      </div>
    </div>
    
    <!-- 添加证据弹窗 -->
    <el-dialog v-model="showEvidenceDialog" title="添加行为证据" width="600px">
      <el-form :model="evidenceForm" label-width="100px">
        <el-form-item label="时间点">
          <el-input v-model="evidenceForm.timeDisplay" disabled />
        </el-form-item>
        
        <el-form-item label="行为类型">
          <el-select v-model="evidenceForm.type" placeholder="选择行为类型">
            <el-option label="积极表现" value="positive" />
            <el-option label="犹豫不决" value="hesitation" />
            <el-option label="情绪变化" value="emotion" />
            <el-option label="技能展示" value="skill" />
            <el-option label="压力反应" value="stress" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="分类">
          <el-select v-model="evidenceForm.category" placeholder="选择分类">
            <el-option label="语言表达" value="verbal" />
            <el-option label="肢体语言" value="nonverbal" />
            <el-option label="情绪反应" value="emotional" />
            <el-option label="问题解决" value="problem-solving" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input 
            v-model="evidenceForm.description" 
            type="textarea" 
            :rows="4"
            placeholder="请详细描述观察到的行为"
          />
        </el-form-item>
        
        <el-form-item label="置信度">
          <el-slider 
            v-model="evidenceForm.confidence" 
            :min="0" 
            :max="100"
            show-input
            :format-tooltip="(val) => `${val}%`"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showEvidenceDialog = false">取消</el-button>
        <el-button type="primary" @click="saveEvidence">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Plus, Edit, Delete, Download, Collection, Back } from '@element-plus/icons-vue'

export default {
  name: 'PlaybackView',
  components: {
    Plus,
    Edit,
    Delete,
    Download,
    Collection,
    Back
  },
  setup() {
    const router = useRouter()
    
    const videoPlayer = ref(null)
    const timelineTrack = ref(null)
    const currentTime = ref(0)
    const duration = ref(0)
    const isPlaying = ref(false)
    const playbackSpeed = ref('1')
    const showEvidenceDialog = ref(false)
    
    const candidate = reactive({
      id: 1,
      name: '张三',
      position: '前端开发工程师',
      interviewDate: '2024-01-15'
    })
    
    const videoUrl = ref('https://sample-video-url.mp4')
    
    const anchorPoints = ref([
      { id: 1, time: 120, label: '自我介绍', stage: '开场' },
      { id: 2, time: 300, label: '技术问题', stage: '专业能力' },
      { id: 3, time: 600, label: '项目经验', stage: '实践经验' },
      { id: 4, time: 900, label: '压力测试', stage: '应变能力' },
      { id: 5, time: 1200, label: '总结陈述', stage: '结尾' }
    ])
    
    const behaviorMarkers = ref([
      { id: 1, time: 150, type: 'hesitation', label: '犹豫', description: '回答技术问题时出现明显停顿' },
      { id: 2, time: 350, type: 'confidence', label: '自信', description: '讲解项目经验时表现自信' },
      { id: 3, time: 480, type: 'emotion', label: '情绪', description: '情绪有明显波动' },
      { id: 4, time: 720, type: 'stress', label: '压力', description: '面对压力问题时有紧张反应' },
      { id: 5, time: 950, type: 'confidence', label: '自信', description: '最后总结时重新恢复自信' }
    ])
    
    const evidenceList = ref([
      {
        id: 1,
        time: 150,
        type: 'hesitation',
        category: 'verbal',
        description: '在回答"请解释闭包概念"时，停顿了约5秒，然后用"嗯..."开始回答，显示出对该概念的不确定性。',
        confidence: 85
      },
      {
        id: 2,
        time: 350,
        type: 'positive',
        category: 'nonverbal',
        description: '讲解项目经验时，手势增多，眼神专注，语速稳定，表现出对该领域的自信和熟练程度。',
        confidence: 92
      },
      {
        id: 3,
        time: 720,
        type: 'stress',
        category: 'emotional',
        description: '面对压力问题时，明显出现微表情变化，眉头轻皱，说话速度加快，显示出一定的紧张情绪。',
        confidence: 78
      }
    ])
    
    const currentAnalysis = reactive({
      emotion: '中性',
      speechRate: 145,
      eyeContact: 75,
      gestureFrequency: 8,
      pauseDuration: 2.3,
      toneVariation: 68
    })
    
    const evidenceForm = reactive({
      time: 0,
      timeDisplay: '00:00',
      type: '',
      category: '',
      description: '',
      confidence: 80
    })
    
    const progressPercentage = computed(() => {
      return duration.value > 0 ? (currentTime.value / duration.value) * 100 : 0
    })
    
    const formatTime = (seconds) => {
      const mins = Math.floor(seconds / 60)
      const secs = Math.floor(seconds % 60)
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    }
    
    const formatDate = (date) => {
      return new Date(date).toLocaleDateString('zh-CN')
    }
    
    const handleTimeUpdate = () => {
      if (videoPlayer.value) {
        currentTime.value = videoPlayer.value.currentTime
        updateCurrentAnalysis()
      }
    }
    
    const handleVideoLoaded = () => {
      if (videoPlayer.value) {
        duration.value = videoPlayer.value.duration
      }
    }
    
    const togglePlay = () => {
      if (videoPlayer.value) {
        if (isPlaying.value) {
          videoPlayer.value.pause()
        } else {
          videoPlayer.value.play()
        }
        isPlaying.value = !isPlaying.value
      }
    }
    
    const seekTo = (time) => {
      if (videoPlayer.value) {
        videoPlayer.value.currentTime = time
        currentTime.value = time
      }
    }
    
    const jumpToTime = (time) => {
      seekTo(time)
    }
    
    const changeSpeed = (speed) => {
      if (videoPlayer.value) {
        videoPlayer.value.playbackRate = parseFloat(speed)
      }
    }
    
    const updateCurrentAnalysis = () => {
      // 根据当前时间更新分析数据
      const time = currentTime.value
      
      // 模拟根据时间变化的分析数据
      if (time < 300) {
        currentAnalysis.emotion = '轻松'
        currentAnalysis.speechRate = 130
        currentAnalysis.eyeContact = 80
      } else if (time < 600) {
        currentAnalysis.emotion = '专注'
        currentAnalysis.speechRate = 145
        currentAnalysis.eyeContact = 85
      } else if (time < 900) {
        currentAnalysis.emotion = '紧张'
        currentAnalysis.speechRate = 160
        currentAnalysis.eyeContact = 65
      } else {
        currentAnalysis.emotion = '自信'
        currentAnalysis.speechRate = 140
        currentAnalysis.eyeContact = 78
      }
    }
    
    const getCurrentEmotionType = () => {
      const emotion = currentAnalysis.emotion
      if (emotion === '自信' || emotion === '轻松') return 'success'
      if (emotion === '专注') return 'primary'
      if (emotion === '紧张') return 'warning'
      return 'info'
    }
    
    const getEvidenceTagType = (type) => {
      const typeMap = {
        positive: 'success',
        hesitation: 'warning',
        emotion: 'info',
        skill: 'primary',
        stress: 'danger'
      }
      return typeMap[type] || 'default'
    }
    
    const addEvidence = () => {
      evidenceForm.time = currentTime.value
      evidenceForm.timeDisplay = formatTime(currentTime.value)
      evidenceForm.type = ''
      evidenceForm.category = ''
      evidenceForm.description = ''
      evidenceForm.confidence = 80
      showEvidenceDialog.value = true
    }
    
    const editEvidence = (evidence) => {
      Object.assign(evidenceForm, {
        ...evidence,
        timeDisplay: formatTime(evidence.time)
      })
      showEvidenceDialog.value = true
    }
    
    const deleteEvidence = (id) => {
      const index = evidenceList.value.findIndex(e => e.id === id)
      if (index > -1) {
        evidenceList.value.splice(index, 1)
      }
    }
    
    const saveEvidence = () => {
      if (evidenceForm.id) {
        // 编辑现有证据
        const index = evidenceList.value.findIndex(e => e.id === evidenceForm.id)
        if (index > -1) {
          evidenceList.value[index] = { ...evidenceForm }
        }
      } else {
        // 添加新证据
        evidenceList.value.push({
          ...evidenceForm,
          id: Date.now()
        })
      }
      
      showEvidenceDialog.value = false
    }
    
    const exportAnalysis = () => {
      // 实现导出分析报告逻辑
      console.log('导出分析报告')
    }
    
    const saveBookmarks = () => {
      // 实现保存书签逻辑
      console.log('保存书签')
    }
    
    const backToReport = () => {
      router.push(`/hr/evaluation/${candidate.id}`)
    }
    
    onMounted(() => {
      // 模拟视频加载
      setTimeout(() => {
        duration.value = 1500 // 25分钟
      }, 500)
    })
    
    return {
      videoPlayer,
      timelineTrack,
      currentTime,
      duration,
      isPlaying,
      playbackSpeed,
      showEvidenceDialog,
      candidate,
      videoUrl,
      anchorPoints,
      behaviorMarkers,
      evidenceList,
      currentAnalysis,
      evidenceForm,
      progressPercentage,
      formatTime,
      formatDate,
      handleTimeUpdate,
      handleVideoLoaded,
      togglePlay,
      seekTo,
      jumpToTime,
      changeSpeed,
      getCurrentEmotionType,
      getEvidenceTagType,
      addEvidence,
      editEvidence,
      deleteEvidence,
      saveEvidence,
      exportAnalysis,
      saveBookmarks,
      backToReport
    }
  }
}
</script>

<style scoped>
.playback-container {
  min-height: 100vh;
  background: #f8f9fa;
  padding: 20px;
}

.playback-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.playback-header h1 {
  color: #333;
  margin: 0;
}

.candidate-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
}

.separator {
  color: #ccc;
}

.playback-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
  margin-bottom: 24px;
}

.video-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.video-player {
  margin-bottom: 24px;
}

.video-player video {
  width: 100%;
  height: 400px;
  border-radius: 8px;
  background: #000;
}

.video-controls {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-top: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.control-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.time-display {
  font-family: monospace;
  color: #666;
  font-size: 14px;
}

.control-center {
  flex: 1;
}

.progress-slider {
  width: 100%;
}

.control-right {
  display: flex;
  align-items: center;
}

.anchor-points h4 {
  color: #333;
  margin-bottom: 16px;
}

.anchor-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.anchor-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.anchor-item:hover {
  background: #e9ecef;
}

.anchor-time {
  font-family: monospace;
  color: #6753C0;
  font-weight: 500;
  min-width: 50px;
}

.anchor-label {
  color: #333;
  font-weight: 500;
}

.anchor-stage {
  color: #666;
  font-size: 12px;
  margin-left: auto;
}

.analysis-panel {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.timeline-section h4,
.evidence-section h4,
.realtime-analysis h4 {
  color: #333;
  margin-bottom: 16px;
}

.timeline-container {
  position: relative;
}

.timeline-track {
  position: relative;
  height: 8px;
  background: #e4e7ed;
  border-radius: 4px;
  margin: 20px 0;
}

.timeline-progress {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background: #6753C0;
  border-radius: 4px;
  transition: width 0.1s;
}

.behavior-marker {
  position: absolute;
  top: -8px;
  transform: translateX(-50%);
  cursor: pointer;
}

.marker-dot {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  border: 2px solid white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.behavior-marker.hesitation .marker-dot {
  background: #f39c12;
}

.behavior-marker.confidence .marker-dot {
  background: #27ae60;
}

.behavior-marker.emotion .marker-dot {
  background: #e74c3c;
}

.behavior-marker.stress .marker-dot {
  background: #e67e22;
}

.marker-label {
  position: absolute;
  top: 32px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 12px;
  color: #666;
  white-space: nowrap;
}

.timeline-legend {
  display: flex;
  gap: 16px;
  margin-top: 16px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.legend-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.legend-dot.hesitation {
  background: #f39c12;
}

.legend-dot.confidence {
  background: #27ae60;
}

.legend-dot.emotion {
  background: #e74c3c;
}

.legend-dot.stress {
  background: #e67e22;
}

.legend-item span {
  font-size: 12px;
  color: #666;
}

.evidence-section {
  max-height: 400px;
  overflow-y: auto;
}

.evidence-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.evidence-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.evidence-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
}

.evidence-header-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.evidence-time {
  font-family: monospace;
  color: #6753C0;
  font-weight: 500;
  cursor: pointer;
  min-width: 50px;
}

.evidence-time:hover {
  text-decoration: underline;
}

.evidence-actions {
  margin-left: auto;
  display: flex;
  gap: 4px;
}

.evidence-content p {
  color: #333;
  margin: 0 0 8px 0;
  line-height: 1.5;
}

.evidence-meta {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #666;
}

.analysis-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.analysis-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f2f5;
}

.analysis-item:last-child {
  border-bottom: none;
}

.analysis-label {
  color: #666;
  font-size: 14px;
}

.analysis-value {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #333;
  font-weight: 500;
}

.playback-footer {
  background: white;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.footer-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
}
</style> 